package cn.hpclub.server.model;

import java.io.IOException;
import java.util.List;

import org.apache.shiro.SecurityUtils;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.security.ShiroPrincipal;

/**
 * 实体类 - 角色
 * 
 */
@TableBind(tableName = "organization")
public class Blankcard extends Model<Blankcard>{
    private static final long     serialVersionUID = 370802114261166318L;
    public static final Blankcard dao              = new Blankcard();

    /**
     * 获取所有Role实体对象集合.
     * 
     * @return Role实体对象集合
     */
    public List<Blankcard> getAllRole(){
        return dao.find("select * from sys_role where is_deleted=0");
    }

    public List<Blankcard> getRoleListByLevel(){
        String sql = "select * from sys_role where is_deleted=0 and level>=(select level from sys_role where id=?)";
        return dao.find(sql, getAdminRoleId());
    }

    private int getAdminRoleId(){
        int adminId = getAdminId();
        SysUserRole userRole = SysUserRole.dao.findFirst("select role_id from sys_user_role where user_id=?", adminId);
        int adminRoleId = userRole.getInt("role_id");
        return adminRoleId;
    }

    private int getAdminId(){
        ShiroPrincipal principal = (ShiroPrincipal)SecurityUtils.getSubject().getPrincipal();
        int adminId = Integer.parseInt(principal.getId());
        return adminId;
    }

    /**
     * @Title: getUserSimCardNum
     * @param orgId
     * @return int
     */
    public int getUsedSimCardCount(int orgId){
        Record record = Db.findFirst(
                                     "select COUNT(1) cnt from sales_promotion where org_id=? and moduleId=3 and return_code = '0'",
                                     orgId);
        int usedNum = record.getLong("cnt").intValue();
        return usedNum;
    }

    /**
     * @Title: getTotalSimCardNum
     * @param orgId
     * @return int
     */
    public int getTotalSimCardNum(int orgId){
        Organization org = Organization.dao.findById(orgId);
        int totalNum = org.getInt("SIMCardCount");
        return totalNum;
    }

    public int getSimCardCountByNumCode(String numCode) throws IOException{
        Blankcard record = findFirst("SELECT id, SIMCardCount from organization where NumCode=?", numCode);
        if(null == record){
            throw new IOException("organization has not found. numCode is " + numCode);
        }
        return record.getInt("SIMCardCount");
    }

    public boolean updateSimCardCountByNumCode(String numCode, int simCardCount){
        if(1 == Db.update("UPDATE organization SET SIMCardCount=? WHERE NumCode=?", simCardCount, numCode)){
            return true;
        } else{
            return false;
        }
    }
}
